#include "logonserver.h"
#include "server/clientsocket.h"
#include "main.h"
#include "utils/Config.h"

LogonServer::LogonServer(QObject *parent) :
    QTcpServer(parent)
{
}

void LogonServer::start()
{
    QHostAddress addr(lanIP);
    if(!listen(addr, TCP_PORT))
    {
        _log->LogIt("Unable to start the TCP server",Logg::LERROR);
    }else{
        _log->LogIt("TCP Server ON");
    }
}

void LogonServer::incomingConnection(int socketDescriptor)
 {
     /*Client *thclient = new Client(socketDescriptor, this);
     connect(thclient, SIGNAL(finished()), thclient, SLOT(deleteLater()));
     thclient->start();*/

     ClientSocket* client = new ClientSocket();
     client->setSocketDescriptor(socketDescriptor);
     connect(client, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
     connect(client,SIGNAL(OnPacket(Packets::TLPacket&)),this,SLOT(OnPacket(Packets::TLPacket&)));
     Handlers::SessionHandler* handler = new Handlers::SessionHandler(client);

     clientConnections.insert(client,handler);
_log->LogIt(QString("Incomming connection from %1:%2").arg(client->peerAddress().toString()).arg(client->peerPort()));
 }
void LogonServer::OnPacket(Packets::TLPacket& pkt)
{
    ClientSocket *client = qobject_cast<ClientSocket *>(sender());
    clientConnections[client]->InPacket(&pkt);
}

void LogonServer::clientDisconnected()
{
    ClientSocket *client = qobject_cast<ClientSocket *>(sender());

    if (!client)
        return;

    clientConnections.remove(client);
    client->deleteLater();
    _log->LogIt(QString("Disconnected from %1:%2").arg(client->peerAddress().toString()).arg(client->peerPort()));
}
